package com.mytijian.openapi.adapter.dianping.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mytijian.openapi.adapter.dianping.dao.DzopenOrderRelDAO;
import com.mytijian.openapi.adapter.dianping.dao.dataobject.DzopenOrderRelDO;
import com.mytijian.openapi.adapter.dianping.dao.param.DzopenOrderRelDAOQuery;
import com.mytijian.openapi.adapter.dianping.exceptions.DzopenErrorInfo;
import com.mytijian.openapi.adapter.dianping.exceptions.DzopenException;
import com.mytijian.openapi.adapter.dianping.model.DzopenOrderRel;
import com.mytijian.openapi.adapter.dianping.param.DzopenOrderRelQuery;
import com.mytijian.openapi.adapter.dianping.service.DzopenOrderRelService;
import com.mytijian.utils.Lists;

@Service("dzopenOrderRelService")
public class DzopenOrderRelServiceImpl implements DzopenOrderRelService {

	@Autowired
	private DzopenOrderRelDAO dzopenOrderRelDAO;
	
	@Override
	public int addDzopenOrderRel(DzopenOrderRel rel) {
		if (rel!=null) {
			DzopenOrderRelDO reldo = new DzopenOrderRelDO();
			BeanUtils.copyProperties(rel, reldo);
			return dzopenOrderRelDAO.insert(reldo);
		}
		return 0;
	}

	@Override
	public int updateDzopenOrderRel(DzopenOrderRel rel) {
		if (rel!=null) {
			DzopenOrderRelDO reldo = new DzopenOrderRelDO();
			BeanUtils.copyProperties(rel, reldo);
			return dzopenOrderRelDAO.update(reldo);
		}
		return 0;
	}

	@Override
	public List<DzopenOrderRel> listOrderRels(DzopenOrderRelQuery query) {
		if (query!=null) {
			DzopenOrderRelDAOQuery daoquery = new DzopenOrderRelDAOQuery();
			BeanUtils.copyProperties(query, daoquery);
			List<DzopenOrderRelDO> dolist = dzopenOrderRelDAO.listOrderRels(daoquery);
			List<DzopenOrderRel> result = new ArrayList<>();
			if (!Lists.isEmpty((dolist))) {
				for (DzopenOrderRelDO reldo : dolist) {
					DzopenOrderRel orderRel = new DzopenOrderRel();
					BeanUtils.copyProperties(reldo, orderRel);
					result.add(orderRel);
				}
			}
			
			return result;
		}
		
		return new ArrayList<>();
	}

	@Override
	public DzopenOrderRel getOrderRel(DzopenOrderRelQuery query) {
		
		List<DzopenOrderRel> rels = listOrderRels(query);
		if (Lists.isEmpty(rels)) {
			return null;
		}
		
		if (rels.size()>1) {
			throw new DzopenException(DzopenErrorInfo.ORDER_BOOK_DUPLICATE_ORDER_ID);
		}
		
		return rels.get(0);
	}

}
